package com.yin.webflux.handler;

import com.yin.webflux.entity.User;
import com.yin.webflux.service.UserService;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * UserHandler
 *
 * @author Yin Guiqing
 */
public class UserHandler {
    private final UserService userService;

    public UserHandler(UserService userService) {
        this.userService = userService;
    }

    public Mono<ServerResponse> getUserById(ServerRequest request) {
        // 获取 id 值
        int id = Integer.parseInt(request.pathVariable("id"));
        // 空值处理
        Mono<ServerResponse> notFound = ServerResponse.notFound().build();
        // 调用 service 得到数据
        Mono<User> userMono = userService.getUserById(id);
        // 把 userMono 进行转换返回，使用 Reactor 操作符 flatMap
        return userMono.flatMap(user -> ServerResponse.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(user)))
                .switchIfEmpty(notFound);
    }

    public Mono<ServerResponse> getAllUsers(ServerRequest request) {
        Flux<User> allUsers = userService.getAllUsers();
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
                .body(allUsers, User.class);
    }

    public Mono<ServerResponse> saveUser(ServerRequest request) {
        Mono<User> userMono = request.bodyToMono(User.class);
        return ServerResponse.ok().build(userService.saveUser(userMono));
    }
}
